﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WP8Demos.Helpers
{
    public static class BindingHelper
    {
        public static readonly DependencyProperty TapProperty =
            DependencyProperty.RegisterAttached("Tap",
            typeof(ICommand), typeof(BindingHelper),
            new PropertyMetadata(null, OnTapPropertyChanged));

        public static void OnTapPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as UIElement;
            if (element == null)
            {
                throw new InvalidOperationException("You can only use the Tap Utility on UIElements");
            }

            var oldCommand = e.OldValue as ICommand;
            if (oldCommand != null)
            {
                element.Tap -= OnTap;
            }

            var newCommand = e.NewValue as ICommand;
            if (newCommand != null)
            {
                element.Tap += OnTap;
            }
        }

        public static ICommand GetTap(UIElement element)
        {
            return (ICommand)element.GetValue(TapProperty);
        }

        public static void SetTap(UIElement element, ICommand value)
        {
            element.SetValue(TapProperty, value);
        }

        public static void OnTap(object sender, GestureEventArgs e)
        {
            var element = sender as UIElement;
            var command = GetTap(element);
            if (command != null && command.CanExecute(e))
            {
                command.Execute((e));
            }
        }
    }
}
